/* gvSIG. Geographic Information System of the Valencian Government
 *
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
 * of the Valencian Government (CIT)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 *
 */
package org.gvsig.raster.osm.swing.impl;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import org.gvsig.i18n.Messages;
import org.gvsig.raster.osm.swing.AddOSMLayerPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Panel to add OSM layers
 * @author Nacho Brodin (nachobrodin@gmail.com)
 */
public class AddOSMLayerPanelImpl extends JPanel implements AddOSMLayerPanel, MouseListener, ActionListener {
	private static final long    serialVersionUID    = 1;
	private static final String  separator           = "*";
	private Logger               log                 = LoggerFactory.getLogger(AddOSMLayerPanelImpl.class);
	private File                 pathToServerList    = null;
	private JTextField           textSelectedServer  = null;
	private JTable               tableServerList     = null;
	private String               propertiesFileName  = "osmservers.properties";
	private JPanel               buttonsPanel        = null;
	private JPanel               selectedServerPanel = null;
	private String[]             columnNames         = null;
	private JButton              addLayerButton      = null;
	private JButton              removeLayerButton   = null;
	private AddServerPanel       serverPanel         = null;
	private JFrame               frame               = null;
	private MouseListener        mouseListener       = null;
	
	public AddOSMLayerPanelImpl(File pathToServerList) {
		if(pathToServerList != null)
			this.pathToServerList = pathToServerList;
		else 
			this.pathToServerList = new File(System.getProperty("user.home"));
		columnNames = new String[]{
			Messages.getText("name"),
			Messages.getText("url"),
			Messages.getText("levels"),
			Messages.getText("format"),};
		frame = new JFrame();
		init();
	}
	
	private void init() {
		GridBagConstraints gridBagConstraints;
		setLayout(new GridBagLayout());
		
		gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 0;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.insets = new Insets(2, 2, 2, 2);
		
		add(getJPanelSelectedServer(), gridBagConstraints);
		
		gridBagConstraints.fill = GridBagConstraints.BOTH;
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.weighty = 1.0;
		
		JScrollPane scrollPane = new JScrollPane(getJTableServerList());
		add(scrollPane, gridBagConstraints);
		
		gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 2;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.weighty = 0.0;
		
		add(getAddServerPanel(), gridBagConstraints);
		
		gridBagConstraints.gridy = 3;
		add(getJPanelButtonsPanel(), gridBagConstraints);
	}
	
	private JPanel getJPanelButtonsPanel() {
		if(buttonsPanel == null) {
			FlowLayout fl = new FlowLayout();
			buttonsPanel = new JPanel(fl);
			addLayerButton = new JButton(Messages.getText("add_server"));
			addLayerButton.addActionListener(this);
			removeLayerButton = new JButton(Messages.getText("remove_server"));
			removeLayerButton.addActionListener(this);
			buttonsPanel.add(addLayerButton, fl);
			buttonsPanel.add(removeLayerButton, fl);
		}
		return buttonsPanel;
	}
	
	private JPanel getJPanelSelectedServer() {
		if(selectedServerPanel == null) {
			selectedServerPanel = new JPanel(new BorderLayout());
			selectedServerPanel.setBorder(BorderFactory.createTitledBorder(Messages.getText("server")));
			selectedServerPanel.add(getJTextFieldSelectedServer(), BorderLayout.CENTER);
		}
		return selectedServerPanel;
	}

	private JTextField getJTextFieldSelectedServer() {
		if(textSelectedServer == null) {
			textSelectedServer = new JTextField();
			textSelectedServer.setEditable(false);
		}
		return textSelectedServer;
	}
	
	private JTable getJTableServerList() {
		if(tableServerList == null) {
			DefaultTableModel model = null;
			try {
				Object[][] objs = loadServerListFromProperties();
				model = new DefaultTableModel(objs, columnNames);
				tableServerList = new JTable(model);
			} catch (FileNotFoundException e) {
				log.debug("Properties file to store servers has not been located");
			} catch (IOException e) {
				log.debug("Error reading properties file which stores servers");
			}
			if(tableServerList == null) {
				model = new DefaultTableModel(null, columnNames);
				tableServerList = new JTable(model);
			}
			ListSelectionModel selectionModel = tableServerList.getSelectionModel();  
	        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			tableServerList.addMouseListener(this);
		}
		return tableServerList;
	}
	
	private Object[][] loadServerListFromProperties() throws FileNotFoundException, IOException {
		if(!new File(getPropertiesFilePath()).exists())
			return null;
		Properties prop = new Properties();
		prop.load(new FileInputStream(getPropertiesFilePath()));
		Collection<Object> collect = prop.values();
		if(collect == null)
			return null;
		
		Iterator<Object> it = collect.iterator();
		Object[][] result = new Object[collect.size()][4];
		
		int cont = 0;
		while(it.hasNext()) {
			String value = (String)it.next();
			result[cont] = value.split("\\" + separator);
			cont ++;
		}
		return result;
	}
	
	
	/*private void addServerToProperties(List<String> line) throws FileNotFoundException, IOException {
		if(!new File(getPropertiesFile()).exists())
			if(!new File(getPropertiesFile()).createNewFile())
				return;
		if(line == null || line.size() != 4)
			return;
		
		Properties prop = new Properties();
		prop.setProperty(line.get(0), 
				line.get(0) + ":" + line.get(1) + ":" + line.get(2) + ":" + line.get(3));
		prop.store(new FileOutputStream(getPropertiesFile()), null);
	}*/

	private void addServerToProperties(String name, String url, String levels, String format) {
			try {
				if(!new File(getPropertiesFilePath()).exists())
					if(!new File(getPropertiesFilePath()).createNewFile())
						return;

				Properties prop = new Properties();
				prop.load(new FileInputStream(getPropertiesFilePath()));
				prop.setProperty(getKeyFromName(name), name + separator + url + separator + levels + separator + format);
				prop.store(new FileOutputStream(getPropertiesFilePath()), null);
			} catch (FileNotFoundException e1) {
				JOptionPane.showMessageDialog(this, Messages.getText("cannot_add_to_file"), Messages.getText("Error"), JOptionPane.ERROR_MESSAGE);
				log.info(Messages.getText("cannot_add_to_file"), e1);
			} catch (IOException e1) {
				JOptionPane.showMessageDialog(this, Messages.getText("cannot_add_to_file"), Messages.getText("Error"), JOptionPane.ERROR_MESSAGE);
				log.info(Messages.getText("cannot_add_to_file"), e1);
			}
	}
	
	private void removeServerFromProperties(String name) {
			try {
				if(!new File(getPropertiesFilePath()).exists())
					return;

				Properties prop = new Properties();
				prop.load(new FileInputStream(getPropertiesFilePath()));
				prop.remove(getKeyFromName(name));
				prop.store(new FileOutputStream(getPropertiesFilePath()), null);
			} catch (FileNotFoundException e1) {
				JOptionPane.showMessageDialog(this, Messages.getText("cannot_remove_from_file"), Messages.getText("Error"), JOptionPane.ERROR_MESSAGE);
				log.info(Messages.getText("cannot_remove_from_file"), e1);
			} catch (IOException e1) {
				JOptionPane.showMessageDialog(this, Messages.getText("cannot_remove_from_file"), Messages.getText("Error"), JOptionPane.ERROR_MESSAGE);
				log.info(Messages.getText("cannot_remove_from_file"), e1);
			}
	}
	
	
	public String getPropertiesFilePath() {
		return pathToServerList.getAbsolutePath() + File.separator + propertiesFileName;
	}

	public void mouseClicked(MouseEvent e) {
		
	}

	public void mouseEntered(MouseEvent e) {
		
	}

	public void mouseExited(MouseEvent e) {
		
	}

	public void mousePressed(MouseEvent e) {
		if(e.getSource() == getJTableServerList()) {
			if(getJTableServerList().getSelectedRow() != -1) {
				int selectedRow = getJTableServerList().getSelectedRow();
				String name = (String)getJTableServerList().getModel().getValueAt(selectedRow, 0);
				getJTextFieldSelectedServer().setText(name);
				if(mouseListener != null)
					mouseListener.mousePressed(e);
			}
		}
	}

	public void mouseReleased(MouseEvent e) {
		
	}
	
	public void addMouseListener(MouseListener listener) {
		this.mouseListener = listener;
	}
	
	public JComponent getComponent() {
		return this;
	}

	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == addLayerButton) {
			if(getAddServerPanel().check()) {
				String name = getAddServerPanel().getJTextFieldName().getText();
				String url = getAddServerPanel().getJTextFieldURL().getText();
				String levels = getAddServerPanel().getJTextFieldLevels().getText();
				String format = getAddServerPanel().getJTextFieldFormat().getText();
				
				int updateRow = existsServerInList(name);
				if(updateRow != -1) {
					int res = JOptionPane.showConfirmDialog(this, Messages.getText("update_existing_row"), Messages.getText("Info"), JOptionPane.INFORMATION_MESSAGE);
					if(res == JOptionPane.YES_OPTION) {
						((DefaultTableModel)getJTableServerList().getModel()).removeRow(updateRow);
					} else {
						return;	
					}
				} 
				((DefaultTableModel)getJTableServerList().getModel()).addRow(new Object[]{name, url, levels, format});
				addServerToProperties(name, url, levels, format);
			}
		}
		
		if(e.getSource() == removeLayerButton) {
			int selected = getJTableServerList().getSelectedRow();
			if(selected != -1) {
				int res = JOptionPane.showConfirmDialog(this, Messages.getText("remove_existing_row"), Messages.getText("Info"), JOptionPane.INFORMATION_MESSAGE);
				if(res == JOptionPane.YES_OPTION) {
					String name = (String)getJTableServerList().getModel().getValueAt(selected, 0);
					((DefaultTableModel)getJTableServerList().getModel()).removeRow(selected);
					getJTextFieldSelectedServer().setText("");
					removeServerFromProperties(name);
				}
			}
		}
 	}
	
	/**
	 * Returns -1 if the element does not exists in the table and its position if exists
	 * @param name
	 * @return
	 */
	private int existsServerInList(String name) {
		for (int i = 0; i < getJTableServerList().getRowCount(); i++) {
			String value = (String)getJTableServerList().getModel().getValueAt(i, 0);
			if(value.equals(name))
				return i;
		}
		return -1;
	}
	
	private String getKeyFromName(String name) {
		return name.replace(' ', '_');
	}
	
	private AddServerPanel getAddServerPanel() {
		if(serverPanel == null) {
			serverPanel = new AddServerPanel(separator);
		}
		return serverPanel;
	}

	public String getPropertiesFileName() {
		return propertiesFileName;
	}
	
	public boolean areSettingsValid() {
		return getJTextFieldSelectedServer().getText() != null && !getJTextFieldSelectedServer().getText().equals("");
	}

	public String getSelectedFormat() {
		if(getSelectedName() == null)
			return null;
		for (int i = 0; i < getJTableServerList().getRowCount(); i++) {
			String value = (String)getJTableServerList().getModel().getValueAt(i, 0);
			if(value.equals(getSelectedName()))
				return (String)getJTableServerList().getModel().getValueAt(i, 3);
		}
		return null;
	}

	public String getSelectedLevel() {
		if(getSelectedName() == null)
			return null;
		for (int i = 0; i < getJTableServerList().getRowCount(); i++) {
			String value = (String)getJTableServerList().getModel().getValueAt(i, 0);
			if(value.equals(getSelectedName()))
				return (String)getJTableServerList().getModel().getValueAt(i, 2);
		}
		return null;
	}

	public String getSelectedName() {
		return getJTextFieldSelectedServer().getText();
	}

	public String getSelectedURL() {
		if(getSelectedName() == null)
			return null;
		for (int i = 0; i < getJTableServerList().getRowCount(); i++) {
			String value = (String)getJTableServerList().getModel().getValueAt(i, 0);
			if(value.equals(getSelectedName()))
				return (String)getJTableServerList().getModel().getValueAt(i, 1);
		}
		return null;
	}
}
